package com.qk.Filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;


@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求地址
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        //判断请求路径是否是登录
        if(uri.contains("/login")){
            log.info("登录请求：{}", uri);
            filterChain.doFilter(request, response);
            return;
        }
        //获取请求头中的token
        String jwt = request.getHeader("token");
        //判断token是否存在，不存在响应401状态码
        if (jwt == null || jwt.equals("")){
            log.info("请求头token为空");
            response.setStatus(401);
            return;
        }
        //存在则解析token，判断是否合法，不合法响应401状态码
        try {
            Claims claims = JwtUtils.parseToken(jwt);
            CurrentUserHoler.setCurrentUser(claims.get("id", Integer.class));
            log.info("当前用户：{}", claims.get("id"));
        } catch (Exception e) {
            log.info("token不合法");
            response.setStatus(401);
        }
        //合法则放行
        log.info("放行");
        filterChain.doFilter(request, response);

        CurrentUserHoler.removeCurrentUser();
        log.info("资源删除");
    }
}
